package com.hwpt.hwaccount.feature.personalinfo;

import android.content.Context;

import com.hwpt.hwaccount.core.data.local.entity.UserEntity;
import com.hwpt.hwaccount.core.data.repository.UserInfoRepository;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class PersonalInfoModel implements PersonalInfoContract.Model {
    private final UserInfoRepository repository;
    private final CompositeDisposable disposables;

    public PersonalInfoModel(Context context) {
        this.repository = new UserInfoRepository(context);
        this.disposables = new CompositeDisposable();
    }

    @Override
    public void getUserInfo(PersonalInfoContract.Model.DataCallback<UserEntity> callback) {
        disposables.add(repository.getAllUsers()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(users -> {
                    if (users != null && !users.isEmpty()) {
                        callback.onSuccess(users.get(0));
                    } else {
                        callback.onError("用户信息不存在");
                    }
                }, throwable -> {
                    callback.onError(throwable.getMessage());
                }));
    }

    @Override
    public void updateUserInfo(UserEntity user, PersonalInfoContract.Model.DataCallback<Boolean> callback) {
        disposables.add(repository.insertUser(user)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(() -> {
                    callback.onSuccess(true);
                }, throwable -> {
                    callback.onError(throwable.getMessage());
                }));
    }

    @Override
    public void updateAvatar(String accountId, String avatarUrl, PersonalInfoContract.Model.DataCallback<Boolean> callback) {
        disposables.add(repository.updateAvatar(accountId, avatarUrl)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(() -> {
                    callback.onSuccess(true);
                }, throwable -> {
                    callback.onError(throwable.getMessage());
                }));
    }

    public void dispose() {
        disposables.clear();
    }
}